﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using TQ.Sharepoint.Webparts.TwitterWebpart.Model;

//using Newtonsoft.Json.Linq;

namespace TQ.Sharepoint.Webparts.TwitterWebpart.Repositories
{
    internal class TrendsRepositories
    {


        internal ListItem[] GetTrending()
        {
            try
            {
                var webRequest = (HttpWebRequest) WebRequest.Create("http://api.twitter.com/1/trends/1.json");
                webRequest.Timeout = -1;
                var webResponse = (HttpWebResponse) webRequest.GetResponse();
                var encode = Encoding.GetEncoding("utf-8");
                var responseStream = new StreamReader(webResponse.GetResponseStream(), encode);
                var contents = responseStream.ReadToEnd();
                var json = contents.TrimStart('[').TrimEnd(']');
                var trendResult = JObject.Parse(json);
                var results = trendResult["trends"];

               return results
                   .Select(tweet => 
                       new Trends{Name = tweet.SelectToken("name").Value<string>(),Query = tweet.SelectToken("query").Value<string>()})
                       .Select(x=>new ListItem{Text = x.Name,Value = x.Query}).ToArray();
            
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Warning);
                var error = new ListItem {Text = ex.Message};
                var errorList = new[] {error};
                return errorList;
            }



        }

    }
}
